package com.hlhj.carview.utils

import android.app.Activity
import android.content.Context
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

object KeyboardUtil {
    fun showK(c: Context) {
        val imm = c.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            ?: return //得到InputMethodManager的实例
        imm.toggleSoftInput(
            InputMethodManager.SHOW_IMPLICIT,
            InputMethodManager.HIDE_NOT_ALWAYS
        )//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
    }
    fun showKeyboard(c:Context,view:View){
        val manager =
            c.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        manager.showSoftInput(view,InputMethodManager.HIDE_NOT_ALWAYS)
    }

    fun hideKeyboard(activity:Activity){
        val manager =
            activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        activity.currentFocus?.let {
            manager.hideSoftInputFromWindow(it.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
        }
        if (activity.currentFocus==null){
            val decorView = activity.window.peekDecorView()
            decorView?.let {
                manager.hideSoftInputFromWindow(decorView.windowToken,0)
            }
        }
    }
    fun isShouldHideInput(v:View?,event:MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val editText = v as EditText
            val leftTop = intArrayOf(0, 0)
            v.getLocationInWindow(leftTop)
            val left = leftTop[0];
            val top = leftTop[1];
            val bottom = top + v.getHeight();
            val right = left + v.getWidth()

            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom)
        }
        return false;
    }

    fun closeKeyboard(view: View) {
        val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}